import _ from "lodash";
import { MarkerPoiEntity } from "../entities/MarkerPoiEntity";
import MarkerModel from "../models/MarkerModel";

export default class MarkerPoiDao {

  static async add(marker: MarkerPoiEntity): Promise<MarkerPoiEntity> {
    try {
      const result = await MarkerModel.create({
        ...marker
      })

      return result.toJSON()

    } catch (err) {

      throw new Error(err.original.message || err.original.code)
    }

  }

  static async getNameByMId(m_id: string) {
    try {
      const result = await MarkerModel.findOne({
        attributes: ["name"],
        where: {
          m_id
        }
      })
      return result
    } catch (err) {
      throw new Error(err.original.message)
    }
  }

  static async del(uid: number, id: string): Promise<boolean> {
    try {
      const result = await MarkerModel.destroy({
        where: {
          u_id: uid,
          id: id
        }
      })

      return result > 0 ? true : false
    } catch (err) {
      throw new Error(err.original.message)
    }

  }

  static async findByUid(uid: number) {

    try {

      const result = await MarkerModel.findAll({
        where: {
          u_id: uid
        }
      })

      return result

    } catch (err) {
      throw new Error(err.original.message)
    }


  }

  static async modify(marker: MarkerPoiEntity): Promise<boolean> {

    try {
      const result = await MarkerModel.update({
        ..._.omit(marker, 'u_id', 'm_id', 'id')
      }, {
        where: {
          u_id: marker.u_id,
          m_id: marker.m_id
        }
      })

      return result[0] > 0 ? true : false
    } catch (err) {
      throw new Error(err.original.message)
    }
  }

  static async findOne(u_id: number, id: string): Promise<object | null> {

    try {
      const result = await MarkerModel.findOne({ where: { u_id, id } })
      if (result === null) {
        return null
      } else {
        return result.toJSON()
      }

    } catch (err) {
      throw new Error(err.original.message)
    }
  }


}